﻿using AutoMapper;
using MediatR;
using MySqlX.XDevAPI.Common;
using Warehouse.Api.Write.AllCation.Command.Breakage;
using Warehouse.Domian.Model;
using Warehouse.ErrorCode;
using Warehouse.Infrastructrue.Implenment;

namespace Warehouse.Api.Write.AllCation.Hanlder
{
    public class AddBreakageCommandHanlder : IRequestHandler<AddBreakageCommand, ApiResult<int>>
    {
        public readonly IBaseRepostity<Breakage> _breakageRepostity;
        public readonly IMapper mapper;
        public readonly Logger<AddBreakageCommandHanlder> logger;

        public AddBreakageCommandHanlder(IBaseRepostity<Breakage> breakageRepostity, IMapper mapper)
        {
            _breakageRepostity = breakageRepostity;
            this.mapper = mapper;
        }
        /// <summary>
        /// 添加破损的记录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public Task<ApiResult<int>> Handle(AddBreakageCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            try
            {
                
                var model = mapper.Map<Breakage>(request);

                int r = _breakageRepostity.InsertAsync(model).Result;
                
                if (r > 0)
                {
                    result.Msg = "添加成功";
                    logger.LogInformation("添加破损记录成功");
                    result.Data = r;
                    result.Code = ApiEume.Success;
                }
                else
                {
                    result.Msg = "添加失败";
                    logger.LogInformation("添加破损记录失败");
                    result.Data = r;
                    result.Code = ApiEume.Error;
                }
                
            }
            catch (Exception ex)
            {
               logger.LogError(ex, "添加破损记录失败");

            }
            return Task.FromResult(result);
        }
    }
}
